﻿using System;
using System.Linq;
using System.Reflection;
using FairyGUI;
using UnityEngine;

namespace Whoot.UI
{
    public static class UIExtension
    {
        public static void AutoFindAllField<T>(this T self) where T : UIPanel
        {
            var fields = self.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
            foreach (var field in fields)
            {
                var attrs = field.GetCustomAttributes<AutoFindAttribute>().ToArray();
                if (attrs.Length <= 0) continue;
                var findInfo = attrs[0];
                var name = string.IsNullOrEmpty(findInfo.Name) ? field.Name : findInfo.Name;
                object obj;
                var type = field.FieldType;
                if (field.FieldType == typeof(Controller))
                {
                    obj = self.ContentPane.GetController(name);
                }
                else if (field.FieldType == typeof(Transition))
                {
                    obj = self.ContentPane.GetTransition(name);
                }
                else
                {
                    obj = self.ContentPane.GetChild(name);
                }

                if (obj == null)
                {
                    throw new Exception("查找子物体失败" + "type=" + field.FieldType + "/name=" + findInfo.Name);
                }

                field.SetValue(self, obj);
            }
        }

        /// <summary>
        /// 自动注册点击事件
        /// </summary>
        /// <param name="self"></param>
        /// <param name="BtnStartName"></param>
        /// <param name="onClick"></param>
        /// <typeparam name="T"></typeparam>
        public static void AutoAddClick<T>(this T self, Action<GComponent> onClick, string BtnStartName = "Btn")
            where T : UIPanel
        {
            for (int i = 0; i < self.ContentPane.numChildren; i++)
            {
                FairyGUI.GObject gObject = self.ContentPane.GetChildAt(i);
                if (gObject.name.StartsWith(BtnStartName))
                {
                    gObject.onClick.Add(a =>
                    {
                        onClick?.Invoke(a.sender as GComponent);
                    });
                }
            }
        }
    }
}